<template>
  <div style="text-align: center">
    <div style="margin-top: 50px;">
      <el-steps :active="active" align-center finish-status="success" >
        <el-step title="验证电子邮件"></el-step>
        <el-step title="重置密码"></el-step>
      </el-steps>
    </div>
    <div v-if="active === 0">
      <div style="margin-top: 80px">
        <div style="font-size: 25px;margin-bottom:10px;font-weight: bold">重置密码</div>
        <div style="font-size: 15px;color: gray">请输入需要重置密码的电子邮件</div>
      </div>
      <div style="margin: 0 20px">
        <el-form :model="form" ref="formRef" :rules="rules" style="width: 100%;margin-top: 50px">
          <el-form-item prop="email">
            <el-input v-model="form.email" type="email" placeholder="电子邮件地址">
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-row :gutter="10" style="width: 100%">
              <el-col :span="17">
                <el-input v-model="form.code" :maxlength="6" type="text" placeholder="请输入验证码">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="5">
                <el-button type="primary" @click="resetConfirmEmail"
                           :disabled="coldTime > 0">
                  {{coldTime > 0 ? '请稍后 ' + coldTime + ' 秒' : '获取验证码'}}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 80px">
        <el-button type="primary" @click="resetConfirm" style="width: 70%">下一步</el-button>
      </div>
    </div>
    <div v-if="active ===1">
      <div style="margin-top: 80px">
        <div style="font-size: 25px;margin-bottom:10px;font-weight: bold">重置密码</div>
        <div style="font-size: 15px;color: gray">请输入新的密码,务必牢记</div>
      </div>
      <div style="margin:0 20px">
        <el-form :model="form" :rules="rules" ref="formRef" style="width: 100%;margin-top: 50px">
          <el-form-item prop="password">
            <el-input v-model="form.password" :maxlength="16" type="password" placeholder="密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password_repeat">
            <el-input v-model="form.password_repeat" :maxlength="16" type="password" placeholder="重复密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 80px">
        <el-button type="danger" @click="resetPassword" style="width: 70%">立刻重置密码</el-button>
      </div>

    </div>

  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import {Lock, Message} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {get,post} from "@/net/index.js";
import router from "@/router/main.js";

const form = reactive({
  email: "",
  code: "",
  password:"",
  password_repeat:""
});
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

const rules = {

  password: [
    {required: true, message: '请输入密码', trigger: ['blur', 'change']},
    {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: ['blur', 'change']}
  ],
  password_repeat: [
    {validator: validatePassword, trigger: ['blur', 'change']}

  ],

  email: [
    {required: true, message: '请输入邮箱地址', trigger: ['blur', 'change']},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: ['blur', 'change']},
  ]
}
const formRef = ref()
const active = ref(0);
let coldTime = ref(0);
function resetConfirm() {
  formRef.value.validate((isValid) => {
    if(isValid) {
      post("/api/auth/resetConfirm",{email: form.email,code: form.code}, () =>{
          active.value++
      })
    }else {
      ElMessage.warning("请填写完整信息")
    }
})
}
function resetPassword() {
  formRef.value.validate((isValid) => {
    if(isValid) {
      post("/api/auth/resetPassword",{email: form.email,code: form.code,password: form.password}, () =>{
        active.value++
        ElMessage.success("重置密码成功")
        console.log("重置密码成功")
        router.push("/")
        console.log("回去")
      })
    }else {
      ElMessage.warning("请填写完整信息")
    }
})
}

const resetConfirmEmail = () => {
  if (coldTime.value > 0) return;

  // 验证邮箱字段
  formRef.value.validateField('email', (errorMessage) => {
    if (!errorMessage) {
      ElMessage.warning("请先填写邮箱");
    } else {
      // 如果邮箱验证通过，则发送验证码
      get(`/api/auth/ask_code?email=${form.email}&type=reset`, () => {
        ElMessage.success("已经发送邮件到" + form.email + "请注意查收");
        coldTime.value = 60;
        const interval = setInterval(() => {
          coldTime.value--;
          if (coldTime.value <= 0) {
            clearInterval(interval);
          }
        }, 1000);
      }, (message) => {
        ElMessage.warning(message);
        coldTime = 0 ;
      });
    }
  });
}
</script>

<style scoped>
/* 添加样式以减少外边距 */
.el-form-item {
  margin-bottom: 20px;
}
</style>
